from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json
from .audit_system import MedicalRecordAuditSystem


@csrf_exempt
@require_http_methods(["POST"])
def audit_medical_records(request):
    """
    API接口：批量审核电子病历
    
    请求格式：
    POST /iterator/audit/
    {
        "batch_size": 10,
        "records": [
            {
                "patient_id": "A12345678",
                "diagnosis": "高血压",
                "medications": ["降压药A", "降压药B"],
                "report_date": "2023-05-15"
            },
            ...
        ]
    }
    
    返回格式：
    {
        "code": 0,
        "msg": "审核完成",
        "data": {
            "total": 100,
            "passed": 95,
            "pass_rate": 95.0
        }
    }
    """
    try:
        # 解析请求数据
        data = json.loads(request.body)
        batch_size = data.get("batch_size", 10)
        records = data.get("records", [])
        
        if not records:
            return JsonResponse({
                "code": 400,
                "msg": "未提供病历数据",
                "data": None
            }, status=400)
        
        # 创建审核系统实例
        audit_system = MedicalRecordAuditSystem(batch_size=batch_size, output_file="audit_results.csv")
        
        # 执行审核
        audit_system.audit_records(records)
        
        # 获取统计信息
        total, passed, pass_rate = audit_system.get_statistics()
        
        return JsonResponse({
            "code": 0,
            "msg": "审核完成",
            "data": {
                "total": total,
                "passed": passed,
                "pass_rate": round(pass_rate, 2)
            }
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            "code": 400,
            "msg": "请求数据格式错误",
            "data": None
        }, status=400)
    except Exception as e:
        return JsonResponse({
            "code": 500,
            "msg": f"服务器错误: {str(e)}",
            "data": None
        }, status=500)